package com.hrpmar.controller;

import com.hrpmar.pojo.Worker;
import com.hrpmar.service.LoginService;
import com.hrpmar.utils.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by dell on 2017/11/28.
 */
@Controller
public class FirstLoginController {


    String msg=null;

    @Resource
    private LoginService loginService;

    @PostMapping("/login")
    @ResponseBody
    public String login(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        Cookie[] cookies = request.getCookies();
        String name = null;
        String pwd = null;
        Integer id = null;
        if(cookies!=null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals("name")) {
                    name = cookies[i].getValue();
                }
                if (cookies[i].getName().equals("pwd")) {
                    pwd = cookies[i].getValue();
                }
                if (cookies[i].getName().equals("id")) {
                    id = Integer.parseInt(cookies[i].getValue());
                }
            }
        }
        Worker worker = null;
        worker = loginService.login(id, name, pwd);
        if (worker != null) {
            session.setAttribute(Constants.LOGIN_USER,worker);
            return "true";
        }else {
            return "false";
        }
    }

    @GetMapping("/cook")
    public String cookie(){
        return "CookLogin";
    }

    @GetMapping("/updateSuccess")
    public String updateSuccess(){
        return "user/updateSuccess";
    }

}
